package com.ckv.qcm.server.filters;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.ckv.qcm.model.User;

public class UserLoginFilter implements Filter {
	
	private String LOGIN_ACTION_URI;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession();
		User user = (User) session.getAttribute("user");
		
		if(user == null && !LOGIN_ACTION_URI.equals(httpRequest.getServletPath())) {
			RequestDispatcher rd = httpRequest.getRequestDispatcher("/login.html");
			rd.forward(request, response);
			return;
		}
		
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		LOGIN_ACTION_URI = filterConfig.getInitParameter("loginActionURI");
	}

}
